import React from 'react';
import { Upload, Icon, Modal } from 'antd';
import { API_HOST } from 'Constants/config';

class PicturesWall extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      previewVisible: false,
      previewImage: '',
      fileList: [],
      id: '',
      img: props.initImg || [],
    };
  }

  componentWillMount() {
    const imgsobj = (this.state.img && this.state.img.length > 0) ? this.state.img.map((k, index) => {
      return {
        uid: k,
        name: `number${index}img`,
        status: 'done',
        url: `${API_HOST}/files/${k}`,
      };
    }) : [];
    this.setState({
      fileList: imgsobj,
    });
  }
  componentWillReceiveProps(nextProps) {
    if (nextProps.isOpen === true && this.props.isOpen === false) {
      const propsimgs = [...nextProps.initImg];
      const imgsobj = propsimgs ? propsimgs.map((k, index) => {
        return {
          uid: k,
          name: `number${index}img`,
          status: 'done',
          url: `${API_HOST}/files/${k}`,
        };
      }) : [];
      this.setState({
        fileList: imgsobj,
        img: propsimgs,
      });
    }
  }
  handleCancel = () => this.setState({ previewVisible: false });
  handlePreview = (file) => {
    this.setState({
      previewImage: file.url || file.thumbUrl,
      previewVisible: true,
    });
  };

  handleChange = ({ fileList, file }) => {
    this.setState({
      fileList,
    });
    if (file.status === 'done') {
      this.setState((prevState) => {
        return {
          img: [...prevState.img, file.response.id],
        };
      }, () => {
        this.props.onChange(this.state.img);
      });
    }
    if (file.status === 'removed') {
      const newimg = this.state.img.filter((k) => {
        return !file.response ?
          k !== file.uid :
          k !== file.response.id;
      });
      this.setState({ img: newimg }, () => {
        this.props.onChange(this.state.img);
      });
    }
  };
  render() {
    const { previewVisible, previewImage, fileList } = this.state;
    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">Upload</div>
      </div>
    );
    return (
      <div className="clearfix">
        <Upload
          action={`${API_HOST}/files`}
          listType="picture-card"
          name="upload_file"
          fileList={fileList}
          withCredentials
          onPreview={this.handlePreview}
          onChange={this.handleChange}
          accept="image/*"
        >
          {fileList.length >= 6 ? null : uploadButton}
        </Upload>
        <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
          <img alt="example" style={{ width: '100%' }} src={previewImage} />
        </Modal>
      </div>
    );
  }
}

export default PicturesWall;
